//模块化，这个js文件只写人员相关的vuex代码
import axios from 'axios';
import { nanoid } from 'nanoid';

export default {
  namespaced: true,
  state: {
    personList: [{ id: '001', name: '张三' }],
  },
  actions: {
    addWang(context, value) {
      if (value.name.indexOf('王') === 0) {
        context.commit('ADDWANG', value);
      } else {
        alert('只能添加姓王的人');
      }
    },
    addRandom(context) {
      axios.get('https://api/uixsj.cn/hitokoto/get?type=social').then(
        response => {
          context.commit('ADDRANDOM', { id: nanoid, name: response.data });
        },
        error => {
          alert(error.message);
        }
      );
    },
  },
  mutations: {
    ADD_PERSON(state, value) {
      state.personList.unshift(value);
    },
    ADDWANG(state, value) {
      state.personList.unshift(value);
    },
    ADDRANDOM(state, value) {
      console.log(value);
      state.personList.unshift(value);
    },
  },
  getters: {
    firstName(state) {
      return state.personList[0].name;
    },
  },
};
